package com.xbongbong.paas.service.recheck;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.pojo.dto.FormDataRepeatDTO;
import com.xbongbong.paas.pojo.vo.CheckRepeatVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.recheck.pojo.RecheckFormRulePojo;
import com.xbongbong.pro.recheck.pojo.dto.RecheckAddEditDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.RecheckingRuleEntity;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @description 机会新建编辑页判重策略实现
 * @author yanglei
 * @date 2022/11/16 18:55
 */
@Service("opportunityRecheckAddEditStrategyImpl")
public class OpportunityRecheckAddEditStrategyImpl extends AbstractRecheckAddEditStrategy {

    private static final Logger LOG = LoggerFactory.getLogger(OpportunityRecheckAddEditStrategyImpl.class);

    @Resource
    private CommonHelp commonHelp;

    @Override
    public Integer businessType() {
        return XbbRefTypeEnum.SALES_OPPORTUNITY.getCode();
    }

    protected void setCommonCondition(RecheckAddEditDTO recheckAddEditDTO, BoolQueryBuilder checkToolBoolQuery,BoolQueryBuilder noRepeatBoolQuery){
        if (commonHelp.isOpenWorkFlow(recheckAddEditDTO.getCorpid())) {
            // 如果开启了工作流，审批中数据会进入主表，查重的时候可以直接从主表查到
            checkToolBoolQuery.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType(), FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
            noRepeatBoolQuery.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType(), FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
        } else {
            checkToolBoolQuery.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
            noRepeatBoolQuery.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        }
        checkToolBoolQuery.filter(termsQuery(ParameterConstant.DEL, Arrays.asList(DelEnum.NORMAL.getDel())));
        noRepeatBoolQuery.filter(termsQuery(ParameterConstant.DEL, Arrays.asList(DelEnum.NORMAL.getDel())));
        checkToolBoolQuery.filter(termQuery(StringConstant.CORPID + ".keyword",recheckAddEditDTO.getCorpid()));
        noRepeatBoolQuery.filter(termQuery(StringConstant.CORPID + ".keyword",recheckAddEditDTO.getCorpid()));
    }

    @Override
    public void setSpecialRecheckAddEditDTO(FormDataRepeatDTO formDataRepeatDTO, RecheckAddEditDTO recheckAddEditDTO, CheckRepeatVO checkRepeatVO) throws XbbException {
        //查重权限
        Boolean recheckPermission = !Objects.equals("-3", formDataRepeatDTO.getUserId()) && formDataRepeatDTO.getLoginUser().getPermSet().contains(ProPermissionAliasEnum.OPPORTUNITY_DUPLICATE.getAlias());
        recheckAddEditDTO.setIsRecheckPermission(recheckPermission);
        recheckAddEditDTO.setSubIndexTypeEnum(IndexTypeEnum.IDX_SAAS_OPPORTUNITY_SUB);
        recheckAddEditDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_OPPORTUNITY);
        recheckAddEditDTO.setNameAttr(SalesOpportunityEnum.NAME.getAttr());
    }

    @Override
    public void handleSystemAttrQueryBuilder(RecheckAddEditDTO recheckAddEditDTO ,BoolQueryBuilder checkToolBoolQuery,BoolQueryBuilder noRepeatBoolQuery) throws XbbException{
        CheckRepeatVO checkRepeatVO = recheckAddEditDTO.getCheckRepeatVO();
        RecheckingRuleEntity ruleEntity = recheckAddEditDTO.getRuleEntity();
        Boolean isEdit = recheckAddEditDTO.getIsEdit();
        try{
            //新建不允许重复规则
            List<RecheckFormRulePojo> noRepeatRule = JSONArray.parseArray(ruleEntity.getNoRepeatRule(), RecheckFormRulePojo.class);
            //查重工具规则
            List<RecheckFormRulePojo> checkToolRule = JSONArray.parseArray(ruleEntity.getCheckToolRule(), RecheckFormRulePojo.class);
            if(isEdit){
                checkRepeatVO.setCheckType(BasicConstant.TWO);
                //代表新建编辑页的鼠标失去焦点动作，需要封装查重工具规则和新建不允许重复规则，拥有查重工具权限才要封装查重工具规则
                if (recheckAddEditDTO.getIsRecheckPermission()){
                    checkRepeatVO.setCheckType(BasicConstant.TWO);
                    handleSystemRecheckingRule(checkToolRule,recheckAddEditDTO,checkToolBoolQuery);
                }
            }
            //否则代表新建编辑保存时的动作，只需要封装新建不允许重复规则
            handleSystemRecheckingRule(noRepeatRule,recheckAddEditDTO,noRepeatBoolQuery);
        }catch (Exception e){
            LOG.error("系统字段查询数据重复出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    protected void handleNameInApproval(RecheckAddEditDTO recheckAddEditDTO) throws XbbException {
        //机会不需要查审批
        return;
    }


}
